var activeRevolvers = [];
function showPageAction(tabId, changeInfo, tab) {
    if(/https?:\/\//.test(tab.url))
    chrome.pageAction.show(tabId);
    setRevolverActive(tabId, false);
};

function isRevolverActiveForTab(tabId) {
    return activeRevolvers.indexOf(tabId)>-1;
}

function setRevolverActive(tabId, isActive) {
    var _index = activeRevolvers.indexOf(tabId);
    if(isActive && _index<0) {
        activeRevolvers.push(tabId);
    }
    else if(!isActive && _index > -1) {
        activeRevolvers.splice(_index ,1);
    }
}

chrome.tabs.onUpdated.addListener(showPageAction);

chrome.pageAction.onClicked.addListener(function(tab) {
    if(isRevolverActiveForTab(tab.id)) {
        chrome.tabs.sendMessage(tab.id, {"message": "deactivate"}, function(response) {
            if(response.message == "OK") {
                playSound();
                setRevolverActive(tab.id, false);
                chrome.pageAction.setIcon({path: "img/icon-19-disabled.png", tabId: tab.id});
            }
        });

    }
    else {
        chrome.tabs.sendMessage(tab.id, {"message": "activate"}, function(response) {
            if(response.message == "OK") {
                playSound();
                setRevolverActive(tab.id, true);
                chrome.pageAction.setIcon({path: "img/icon-19.png",
                    tabId: tab.id});
            }
        });
    }
});

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.setting)
            sendResponse({value: localStorage.getItem(request.setting)});
        else if(request.action == "screenshot") {
            chrome.tabs.captureVisibleTab(null, null, function(image){
                chrome.tabs.sendMessage(sender.tab.id, {"message": "screenshot", image:image, x:request.x, y:request.y, w:request.w, h:request.h, x1:request.x1,y1:request.y1}, function(response) {   });
            });
        }
    });


window.addEventListener("storage", function() {
    for(var i =0 ;i<activeRevolvers.length; i++) {
        if(activeRevolvers[i]) {
            chrome.tabs.sendMessage(i-0, {"message": "settings"}, function(response) {

            });
        }
    }

}, false);

function playSound() {
    var sound = new Audio();
    sound.src="sound/reload3.wav";
    sound.volume = localStorage.getItem("volume") || 0.8;
    sound.play();
}